<template>
  <div>
   <el-space>
      <el-button
        :type="dateRange === 'week' ? 'primary' : ''"
        @click="dateRange = 'week'; load()"
      >
        本周
      </el-button>
      <el-button
        :type="dateRange === 'month' ? 'primary' : ''"
        @click="dateRange = 'month'; load()"
      >
        本月
      </el-button>
    </el-space>


    <!-- 销售趋势 -->
    <el-card class="mt">
      <template #header>销售额趋势</template>
      <div ref="salesRef" style="height: 300px"></div>
    </el-card>

    <!-- 菜品排行 -->
    <el-card class="mt">
      <template #header>菜品销量 TOP-10</template>
      <div ref="dishRef" style="height: 300px"></div>
    </el-card>

    <!-- 支付渠道占比 -->
    <el-card class="mt">
      <template #header>支付渠道占比</template>
      <div ref="payRef" style="height: 300px"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import isoWeek from 'dayjs/plugin/isoWeek'
dayjs.extend(isoWeek)

import { raw } from '@/api/raw'
import { useAuthStore } from '@/stores/auth'
import { jwtDecode } from 'jwt-decode'

interface JwtPayload {
  storeId: number
}

const auth = useAuthStore()
const storeId = ref<number | null>(
  auth.token ? (jwtDecode<JwtPayload>(auth.token) as JwtPayload).storeId : null
)

/* 当前视图：week | month */
const dateRange = ref<'week' | 'month'>('month')

/* 图表实例 */
const salesRef = ref<HTMLElement>()
const dishRef = ref<HTMLElement>()
const payRef = ref<HTMLElement>()
let salesChart: echarts.ECharts
let dishChart: echarts.ECharts
let payChart: echarts.ECharts

/* 数据 */
const salesData = ref<any[]>([])
const dishData = ref<any[]>([])
const payData = ref<any[]>([])

/* 加载数据 */
const load = async () => {
  if (!storeId.value) return

  let start: string
  let end: string

  if (dateRange.value === 'week') {
    // 周一 → 周日
    start = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
    end = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD')
  } else {
    // 本月第一天 → 最后一天
    start = dayjs().startOf('month').format('YYYY-MM-DD')
    end = dayjs().endOf('month').format('YYYY-MM-DD')
  }

  const [s, d, p] = await Promise.all([
    raw.get('/manager/report/sales', { params: { storeId: storeId.value, start, end } }),
    raw.get('/manager/report/dish-rank', { params: { storeId: storeId.value, start, end, top: 10 } }),
    raw.get('/manager/report/pay-channel', { params: { storeId: storeId.value, start, end } })
  ])

  salesData.value = Array.isArray(s.data?.data) ? s.data.data : []
  dishData.value = Array.isArray(d.data?.data) ? d.data.data : []
  payData.value = Array.isArray(p.data?.data) ? p.data.data : []

  renderCharts()
}

/* 渲染图表 */
const renderCharts = () => {
  /* 销售趋势 */
  salesChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 10, top: 10, bottom: 30 },
    xAxis: { type: 'category', data: salesData.value.map(i => i.date) },
    yAxis: { type: 'value' },
    series: [{ data: salesData.value.map(i => i.sales), type: 'line', smooth: true }]
  })

  /* 菜品排行 */
  dishChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 10, top: 10, bottom: 30 },
    xAxis: { type: 'category', data: dishData.value.map(i => i.dishName) },
    yAxis: { type: 'value' },
    series: [{
      data: dishData.value.map(i => i.sold),
      type: 'bar',
      itemStyle: { color: '#5470c6' }
    }],
    graphic: dishData.value.length ? undefined : {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: { text: '暂无数据', fontSize: 20, fill: '#999' }
    }
  })

  /* 支付渠道占比 */
  payChart.setOption({
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: '60%',
      center: ['50%', '50%'],
      data: payData.value.map(i => ({ name: i.channel, value: i.amount })),
      label: { formatter: '{b}: {c} ({d}%)' }
    }],
    graphic: payData.value.length ? undefined : {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: { text: '暂无数据', fontSize: 20, fill: '#999' }
    }
  })
}

/* 初始化 */
onMounted(() => {
  salesChart = echarts.init(salesRef.value!)
  dishChart = echarts.init(dishRef.value!)
  payChart = echarts.init(payRef.value!)
  load()
})
</script>

<style scoped>
.mt {
  margin-top: 16px;
}
</style>